﻿#include "epollpoll.h"
#include "socketfd.h"
#include "socketlibfunction.h"
#include <stdio.h>

SocketLib::EpollPoll::EpollPoll()
{
    m_epollFD = epoll_create(256);
}

void SocketLib::EpollPoll::doPoll(long    aTimeout)
{
    int nfds = epoll_wait(m_epollFD, m_eventList, 20, 50);

    for (int i = 0; i < nfds; ++i)
    {
        bool fdsus = false;

        SocketFD* currentfd = (SocketFD*)(m_eventList[i].data.ptr);

        if (NULL != currentfd)
        {
            uint32_t events = m_eventList[i].events;

            if (events & EPOLLIN)
            {
                fdsus = currentfd->onRead();
            }

            if (fdsus && events & EPOLLOUT)
            {
                fdsus = currentfd->onSend();
            }
        }

        if (fdsus)
        {
            motifyFdEvent(currentfd, EPOLLIN | EPOLLOUT | EPOLLET);

        }
        else
        {
            delSocketFD(currentfd);

            SocketApi::CloseSocket(currentfd->getSocketFD());
            currentfd->onClose();
        }
    }
}

void SocketLib::EpollPoll::addSocketFD(SocketFD* pSocketFD)
{
    m_tempEvent.data.fd = pSocketFD->getSocketFD();
    m_tempEvent.events = EPOLLIN | EPOLLET;
    m_tempEvent.data.ptr = pSocketFD;
    epoll_ctl(m_epollFD, EPOLL_CTL_ADD, pSocketFD->getSocketFD(), &m_tempEvent);
}

void SocketLib::EpollPoll::delSocketFD(SocketFD* pSocketFD)
{
    m_tempEvent.data.fd = pSocketFD->getSocketFD();
    m_tempEvent.data.ptr = pSocketFD;
    m_tempEvent.events = EPOLLET;

    epoll_ctl(m_epollFD, EPOLL_CTL_DEL, pSocketFD->getSocketFD(), &m_tempEvent);
}

void SocketLib::EpollPoll::motifyFdEvent(SocketFD* pSocketFD, uint32_t pEvent)
{
    m_tempEvent.data.fd = pSocketFD->getSocketFD();
    m_tempEvent.data.ptr = pSocketFD;
    m_tempEvent.events = pEvent;

    epoll_ctl(m_epollFD, EPOLL_CTL_MOD, pSocketFD->getSocketFD(), &m_tempEvent);
}

void SocketLib::EpollPoll::onPollError()
{

}
